/*
 * IBM Corporation.
 * Copyright (c) 2014 All Rights Reserved.
 */

package com.ibm.iisp.common.dao.openjpa;

import java.util.Date;

import org.apache.openjpa.event.LifecycleEvent;
import org.apache.openjpa.event.PersistListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.context.SecurityContextHolder;

import com.ibm.iisp.common.vo.AuditVO;

/**
 * 类作用：
 * @author Johnny@cn.ibm.com
 * 使用说明：
 */
public class AuditPersistListener implements PersistListener {
	private Logger log = LoggerFactory.getLogger(getClass());

	/* (non-Javadoc)
	 * @see org.apache.openjpa.event.PersistListener#beforePersist(org.apache.openjpa.event.LifecycleEvent)
	 */
	@Override
	public void beforePersist(LifecycleEvent event) {
		if (event.getRelated() instanceof AuditVO){
			String username = SecurityContextHolder.getContext().getAuthentication().getName();
			AuditVO vo = (AuditVO) event.getRelated();
			log.trace("audit vo tercepted {}, {}", vo, username);
			vo.setLastUpdateUser(username);
			if (vo.getCreateUser() == null) {
				vo.setCreateUser(username);
				vo.setCreateTime(new Date());
			}
			
		}

	}

	/* (non-Javadoc)
	 * @see org.apache.openjpa.event.PersistListener#afterPersist(org.apache.openjpa.event.LifecycleEvent)
	 */
	@Override
	public void afterPersist(LifecycleEvent event) {
		// TODO Auto-generated method stub

	}

}
